<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Page;
class stuController extends Controller
{

    function __construct()
    {
        parent::__construct();
        $this->check_auth(); //检查权限

        $sh_class = M("shclass");
        $sh_class_array = $sh_class->select();
        $sh_grade = M("grade");
        $sh_grade_array = $sh_grade->where("is_inschool=0") ->order("id DESC")->select();

        $this->assign('sh_class_array', $sh_class_array);
        $this->assign('sh_grade_array', $sh_grade_array);

    }

    public function showAll()
    {
        $stu_model = M('stu');
        //导入分页助手类
        import('Org.Util.Page');
        $map['t.school_id'] = $_SESSION['school_id'];  //只能查看本校的
        $_REQUEST['poor'] = isset($_REQUEST['poor']) ? $_REQUEST['poor'] : -1;
        $_REQUEST['liushou'] = isset($_REQUEST['liushou']) ? $_REQUEST['liushou'] : -1;
        $_REQUEST['term'] = isset($_REQUEST['term']) ? $_REQUEST['term'] : -1;
        $_REQUEST['grade'] = isset($_REQUEST['grade']) ? $_REQUEST['grade'] : -1;
        $_REQUEST['class'] = isset($_REQUEST['class']) ? $_REQUEST['class'] : -1;
        $action = $_REQUEST['action'];
        //   echo $action;
        //   die();
        if ($_REQUEST['poor'] != -1) {
            $map['poor'] = $_REQUEST['poor'];
        }
        if ($_REQUEST['liushou'] != -1) {
            $map['liushou'] = $_REQUEST['liushou'];
        }
        if ($_REQUEST['term'] != -1) {
            $map['term'] = $_REQUEST['term'];
        }
        if ($_REQUEST['grade']!= -1) {
            $map['grade'] = $_REQUEST['grade'];
        }
        if ($_REQUEST['class']!= -1) {
            $map['class'] = $_REQUEST['class'];
        }
        $kw = $_REQUEST['kw'];
        $where['t.name'] = array('like', "%{$kw}%");
        $where['t.ID_number'] = array('like', "%{$kw}%");
        $where['t.XJ_number'] = array('like', "%{$kw}%");
        $where['t.mother_tel'] = array('like', "%{$kw}%");
        $where['t.father_tel'] = array('like', "%{$kw}%");
        $where['_logic'] = 'or';
        $map['_complex'] = $where;

        if(date("m")>'01' && date('m')<'09' ){
            $current_term = date("Y") . "春";
        }elseif(date("m")=='01'){
            $current_term = (date("Y")-1) . "秋";
        }else{
            $current_term = date("Y") . "秋";
        }

        $fields = $_REQUEST['fields'];
        if (in_array("t.father_name", $fields)) {
            $fields[] = "t.mother_name";
        }
        if (in_array("t.father_ID_number", $fields)) {
            $fields[] = "t.mother_ID_number";
        }
        if (in_array("t.father_tel", $fields)) {
            $fields[] = "t.mother_tel";
        }
        $current_year = date("Y")-2;
        for ($current_year; $current_year<=date("Y"); $current_year++) {
            $term[] = $current_year . "春";
            $term[] = $current_year . "秋";
        }
        //var_dump($term);
        $total = $stu_model
            ->alias('t')
            ->field('t.ID_number')
            ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
            ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
            ->join('left join ' . C('DB_PREFIX') . 'stu_sign as s on t.id = s.stu_id')
         //   ->join('left join ' . C('DB_PREFIX') . 'stu_sign as s on t.id = s.stu_id and s.term="'.$current_term.'"')

            ->where($map)
            ->group('t.ID_number')
            ->order("t.id ASC")
            ->select();
        $page_size = 50;
        $total = count($total);
        $page = new Page($total, $page_size);
        $page->setConfig("header", '个用户');
        $pageControl = $page->show();

        if ($_REQUEST['term']!= -1) {
            $strsql=' and s.term="'.$_REQUEST['term'].'"';
        }

       $stus = $stu_model
            ->alias('t')
            ->field('t.*,c.name as classname,g.name as gradename,s.otime')
            ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
            ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
           ->join('left join ' . C('DB_PREFIX') . 'stu_sign as s on t.id = s.stu_id '.$strsql)
            ->where($map)
            ->group('t.ID_number')
            ->order("t.id ASC")
            ->limit($page->firstRow,$page->listRows)
            ->select();
     //  echo $stu_model->_sql();

        // die();
        $pn = $_REQUEST['p'] ? $_REQUEST['p'] : 1;
        foreach ($stus as $k=>$v){
            $stus[$k]['ids'] = $k+1+($pn-1)*$page_size;
            if($v['otime']){
                $stus[$k]['otime'] = date('Y-m-d H:i',$v['otime']);
            }else{
                $stus[$k]['otime'] = '未注册';
            }
            if(!$v['father_name']){
                $stus[$k]['father_name'] = $v['mother_name'];
            }
            if(!$v['father_tel']){
                $stus[$k]['father_tel'] = $v['mother_tel'];
            }
        }

        if ($action == "excel") {

            if(!$fields){
                $fields=array(
                    't.name',
                    't.sex',
                    't.ID_number',
                    't.XJ_number',
                    'g.name as gradename',
                    'c.name as classname',
                    't.jiguan',
                    't.town',
                    't.address' ,
                    't.father_name',
                    't.father_ID_number',
                    't.father_tel',
                 //   't.liushou',
                 //   't.laiyuan',
                    't.poor'
                );
            }

            if (in_array('t.poor', $fields)) {
                $fields[] = 't.poor_teacher';
            }
            $stus = $stu_model
                ->alias('t')
                ->field(implode(",",$fields))
                ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
                ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
                ->join('left join ' . C('DB_PREFIX') . 'stu_sign as s on t.id = s.stu_id')
                ->where($map)
                ->order("t.id DESC")
                ->select();
            //  echo $stu_model->_sql();

           // var_dump($stus);

            $excel=array(
                't.name' => '姓名',
                't.sex' => '性别',
                't.ID_number' => '身份证号',
                't.XJ_number' => '学籍号',
                'g.name as gradename' => '年级',
                'c.name as classname' => '班级',
                't.jiguan' => '籍贯',
                't.town' => '乡镇',
                't.address' => '住址',
                't.father_name' => '家长姓名',
                't.father_ID_number' => '家长身份证号',
                't.father_tel' => '联系电话',
                't.liushou' => '留守儿童',
                't.laiyuan' => '生源地',
                't.poor' => '是否贫困户'
            );
            $excel_colspan=array("B","C","D","E","F","G","H","I","J","K","L","M","N");

            if (in_array('t.poor', $fields)) {
                //存在扶贫数据
                $excel['t.poor_teacher'] = '帮扶教师ID';
                $excel['bf_teacher'] = '帮扶教师';
                $excel['bf_teacher_mobile'] = '帮扶教师联系方式';
                $excel_colspan[] = 'O';
                $excel_colspan[] = 'P';
                $excel_colspan[] = 'Q';
            }

            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5", '', '.php');
            import("Org.Util.PHPExcel.IOFactory", '', '.php');

            $objPHPExcel = new \PHPExcel();


// Set document properties
            $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                ->setLastModifiedBy("Maarten Balliauw")
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");

            if (in_array('t.poor', $fields)) {
                $fields[] = 'bf_teacher';
                $fields[] = 'bf_teacher_mobile';
            }
       //     var_dump($fields);
       //     var_dump($excel_colspan);
      //      var_dump($excel);



            $objPHPExcel->setActiveSheetIndex(0);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '序号');
                foreach($fields as $kf=>$vf){
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($excel_colspan[$kf] . '1', $excel[$vf]);
                 //   echo 'setCellValue('.$excel_colspan[$kf] . '1', $excel[$kf].')<br>';
                }

         //   die();
            foreach ($stus as $k => $v) {


                if($v['father_name']==""){
                    $v['father_name'] = $v['mother_name'];
                    unset($v['mother_name']);
                }
                if($v['father_tel']==""){
                    $v['father_tel'] = $v['mother_tel'];
                    unset($v['mother_tel']);
                }
                if($v['father_id_number']==""){
                    $v['father_id_number'] = $v['mother_id_number'];
                   unset($v['mother_id_number']);
                }
                $teacher = M('teacher');

                if($v['poor_teacher']){
                $bf_teacher=$teacher->where(array("id"=>$v['poor_teacher']))->find();
                $v['bf_teacher'] = $bf_teacher['name'];
                $v['bf_teacher_mobile'] = $bf_teacher['mobile'];
                }
//处理数据完成

                 $num = $k + 2;
                $objPHPExcel->setActiveSheetIndex(0)
                    //Excel的第A列，uid是你查出数组的键值，下面以此类推
                    ->setCellValue('A' . $num, $num-1);
                foreach($fields as $kf=>$vf){
                    if(strstr($vf, 'number')){
                        $fgs = '  ';
                    }else{
                        $fgs = "";
                    }
                    $v=array_values($v);
                    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($excel_colspan[$kf] . $num, $fgs.$v[$kf]);
                 //   echo 'setCellValue('.$excel_colspan[$kf] . $num, $fgs.$v[$kf].')';
                }
           //     var_dump($objPHPExcel);
             //   die();
             }


            $objPHPExcel->getActiveSheet()->setTitle('导出数据包');
            $objPHPExcel->setActiveSheetIndex(0);
            $filename = '导出数据包' . date('YmdHis');
            ob_end_clean();//清除缓冲区,避免乱码
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            //   $objWriter = \PHPExcel_IOFactory::createReader('Excel5');
            //  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;

        }


        $this->assign('stus', $stus);
        $this->assign('term', $term);
        $this->assign('count', $total);
        $this->assign('page_title', "学生列表");
        $this->assign('pageControl', $pageControl);
        $this->display();

    }
    public function show_tj()
    {
        $stu_model = M('stu');
        //导入分页助手类
        import('Org.Util.Page');
        $map['t.school_id'] = $_SESSION['school_id'];  //只能查看本校的

        $_REQUEST['poor'] = isset($_REQUEST['poor']) ? $_REQUEST['poor'] : -1;


        if(date("m")>'01' && date('m')<'09' ){
            $current_term = date("Y") . "春";
        }elseif(date("m")=='01'){
            $current_term = (date("Y")-1) . "秋";
        }else{
            $current_term = date("Y") . "秋";
        }

        $_REQUEST['term'] = isset($_REQUEST['term']) ? $_REQUEST['term'] :$current_term;

        if ($_REQUEST['poor'] != -1) {
            $map['poor'] = $_REQUEST['poor'];
        }
        if ($_REQUEST['term'] != -1) {
            $map['term'] = $_REQUEST['term'];
        }

        if ($_REQUEST['grade']) {
            $map['grade'] = $_REQUEST['grade'];
        }
        if ($_REQUEST['class']) {
            $map['grade'] = $_REQUEST['grade'];
        }



        $current_year = date("Y")-2;
        for ($current_year; $current_year<=date("Y"); $current_year++) {
            $term[] = $current_year . "春";
            $term[] = $current_year . "秋";
        }



       $stus = $stu_model
            ->alias('t')
            ->field('s.term,c.name as classname,g.name as gradename,t.sex,count(DISTINCT t.ID_number) as number')
            ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
            ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
            ->join('left join ' . C('DB_PREFIX') . 'stu_sign as s on t.id = s.stu_id')
            ->where($map)
           ->group('s.term,t.grade,t.class,t.sex')
            ->order("term ASC,gradename ASC,classname ASC")
            ->select();

        $stus_class = $stu_model
            ->alias('t')
            ->field('s.term,c.name as classname,g.name as gradename,t.sex,count(DISTINCT t.ID_number) as number')
            ->join('left join ' . C('DB_PREFIX') . 'shclass as c on c.id = t.class')
            ->join('left join ' . C('DB_PREFIX') . 'grade as g on g.id = t.grade')
            ->join('left join ' . C('DB_PREFIX') . 'stu_sign as s on t.id = s.stu_id')
            ->where($map)
           ->group('s.term,t.grade,t.class')
            ->order("term ASC,gradename ASC,classname ASC")
            ->select();

        $page_total = 0;
        foreach ($stus_class as $ks=>$vs){
            if(!$vs['term']){
                $vs['term'] = '未注册';
            }

            foreach ($stus as $k=>$v){
                if(!$v['term']){
                    $v['term'] = '未注册';
                }
               if($v['classname']==$vs['classname'] && $v['gradename']==$vs['gradename'] && $v['term']==$vs['term']){
                   $vs[$v['sex']] = $v['number'];
                   $vs['he'] += $v['number'];
               }
            }
            $stus_class[$ks] = $vs;
            $page_total += $vs['he'];
        }



        $this->assign('stus', $stus_class);

        $this->assign('term', $term);
        $this->assign('page_total', $page_total);

        $this->assign('page_title', "学生数统计");

        $this->display();

    }

    //实现学生修改功能
    public function update()
    {
        header("Content-Type:text/html;charset=utf-8");
        $stu = M('stu');
        $id = $_GET['id'];
        if (!$_POST['name']) {
            $this->error('姓名不能为空！！');
        }
        $IDCard = $_POST['ID_number'];
        $tyear = intval(substr($IDCard, 6, 4));
        $tmonth = intval(substr($IDCard, 10, 2));
        $tday = intval(substr($IDCard, 12, 2));
        $_POST['birthday'] = $tyear . '-' . $tmonth . '-' . $tday;
        if ($id) {
            // $birth = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8);
            // $sex = substr($idcard, (strlen($idcard)==15 ? -2 : -1), 1) % 2 ? '男' : '女';

            $stu_list = $stu->where("id=$id")->save($_POST);

            if ($stu_list) {
                $this->success('修改成功！！');
                $this->redirect('showAll');
            } else {
                $this->error('修改失败！！');
            }
        } else {
            $result = $stu->add($_POST);
            if ($result) {
                $this->success('添加成功！！');
                $this->redirect('showAll');
            } else {
                $this->error('添加失败！！');
            }
        }

        $this->redirect('showAll');//重定向到控制器的方法  display是本控制的方法

    }

    public function showUpdate()
    {
        $stu = M('stu');
        $id = $_GET['id'];
        $stu_list = $stu->where("id=$id")->find();

        $teacher_class = M("teacher");
        $teacher_array = $teacher_class->select();
        $this->assign('teacher_array',$teacher_array);

        $this->assign('page_title', "修改");
        $this->assign('user_list', $stu_list);
        $this->display('update');
    }

    //实现学生删除功能
    public function del()
    {
        $stu = M('stu');
        $id = $_GET['id'];
        $stu->where("id=$id")->delete();
        $this->redirect('showAll');//重定向到控制器的方法  display是本控制的方法
    }


    public function showAdd()
    {
        $this->assign('user_list', array('poor'=>0));
        $this->display('update');
    }

    public function upload()
    {
        ini_set('memory_limit', '1024M');
        if (!empty($_FILES)) {
            $config = array(
                'exts' => array('xlsx', 'xls'),
                'maxSize' => 3145728000,
                'rootPath' => "./Public/",
                'savePath' => 'Uploads/',
                'subName' => array('date', 'Ymd'),
            );
            $upload = new \Think\Upload($config);
            $grade_model = M("grade");
            $class_model = M("shclass");
            $info = $upload->upload();
            if (!$info) {
                $this->error($upload->getError());
            } else {//上传成功拼接获得上传文件的地址
                // $filename=ROOT.'/Public'.$info['excel']['savepath'].$info['excel']['savename'];
                $filename = $upload->rootPath . $info['files']['savepath'] . $info['files']['savename'];
                require_once THINK_PATH.'Library/Org/Util/PHPExcel/IOFactory.php';
                $reader =\PHPExcel_IOFactory::createReader('Excel5');
                $PHPExcel = $reader->load($filename);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumm = $sheet->getHighestColumn(); // 取得总列数
                $data = array();
                $stu_model = M('stu');
                for ($row = 2; $row <= $highestRow; $row++){//行数是以第1行开始
                    $dataset = array();
                    for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
                        $dataset[] = $sheet->getCell($column.$row)->getValue();
                    }
                    //查询是否存在
                    $stus = $stu_model->where(array('ID_number'=>$dataset[3],'name'=>$dataset[1]))->find();

                    //如果姓名为空，全部跳出
                    if(!$dataset[1]){
                        break;
                    }

                    //变量准备开始
                    $gc = $dataset[6];
                    $grade = substr($gc, 0, 7);
                    $class = substr($gc, 7, 10);

                    $grade_array=$grade_model->where(array("name"=>$grade))->find();
                    if($class){
                        $class_array=$class_model->where(array("name"=>$class))->find();
                    }else{
                        $class_array['id'] = 22;
                    }

                    $jiguan = substr($dataset[8],0,9);
                    $address = str_replace($jiguan,"",$dataset[8]);
                    $address_array = explode('镇', $address);
                    if(count($address_array)>1){
                        $town = $address_array[0];
                        $address=$address_array[1];
                    }else{
                        $town="";
                        $address=$address_array[0];
                    }


                    $IDCard = $dataset[3];//身份证号
                    $tyear = intval(substr($IDCard, 6, 4));
                    $tmonth = intval(substr($IDCard, 10, 2));
                    $tday = intval(substr($IDCard, 12, 2));
                    $birthday = $tyear . '-' . $tmonth . '-' . $tday;

                    $insert_data=array(
                        'name' => $dataset[1],
                        'sex' => $dataset[2],
                        'ID_number' => $dataset[3],
                        'XJ_number' => $dataset[4],
                        'birthday' => $birthday,
                        'grade' => $grade_array['id'],
                        'class' => $class_array['id'],
                        'jiguan' => $jiguan,
                        'town' => $town,
                        'address' => $address
                    );

                    if(substr($dataset[1],0,3)==substr($dataset[9],0,3)){
                        $insert_data['father_name'] = $dataset[9];
                        $insert_data['father_ID_number'] = $dataset[10];
                        $insert_data['father_tel'] = $dataset[11];
                    }else{
                        $insert_data['mother_name'] = $dataset[9];
                        $insert_data['mother_ID_number'] = $dataset[10];
                        $insert_data['mother_tel'] = $dataset[11];
                    }
                    if($dataset[12]=='是'){
                        $insert_data['poor'] = 1;
                    }else{
                        $insert_data['poor'] = 0;
                    }
                    //变量完成


                    if($stus){
                        //存在，更新学籍号
                        $stu_list = $stu_model->where("id=".$stus['id'])->save($insert_data);
                    }else{
                        $result = $stu_model->add($insert_data);
                    }

                }

                //数据导入成功之后的跳转操作
                $this->success('导入成功', U('Admin/Stu/showAll'), 3);
            }
        }

    }
    public function zupload2()
    {
        ini_set('memory_limit', '1024M');
        if (!empty($_FILES)) {
            $config = array(
                'exts' => array('xlsx', 'xls'),
                'maxSize' => 3145728000,
                'rootPath' => "./Public/",
                'savePath' => 'Uploads/',
                'subName' => array('date', 'Ymd'),
            );
            $upload = new \Think\Upload($config);

            $info = $upload->upload();
            if (!$info) {
                $this->error($upload->getError());
            } else {//上传成功拼接获得上传文件的地址
                // $filename=ROOT.'/Public'.$info['excel']['savepath'].$info['excel']['savename'];
                $filename = $upload->rootPath . $info['files']['savepath'] . $info['files']['savename'];
                require_once THINK_PATH.'Library/Org/Util/PHPExcel/IOFactory.php';
                $reader =\PHPExcel_IOFactory::createReader('Excel5');
                $PHPExcel = $reader->load($filename);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumm = $sheet->getHighestColumn(); // 取得总列数
                $data = array();
                $stu_model = M('stu');
             //   var_dump($stu_model);
             //   die();
                for ($row = 2; $row <= $highestRow; $row++){//行数是以第1行开始
                    $dataset = array();
                    for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
                        $dataset[] = (string)$sheet->getCell($column.$row)->getValue();
                    }

                    //查询是否存在
                    $stus = $stu_model->where(array('ID_number'=>$dataset[3]))->find();
                    if($stus){

                        $insert_data=array(
                            'laiyuan' => $dataset[4]
                        );
                        var_dump($insert_data);
                        var_dump($stus);
                       // die();
                        $stu_list = $stu_model->where("id=".$stus['id'])->save($insert_data);
                      //  var_dump($insert_data);

                    }


                }
            echo "OVER";
                //数据导入成功之后的跳转操作

            }
        }

    }
    public function zupload()
    {
        ini_set('memory_limit', '1024M');
        if (!empty($_FILES)) {
            $config = array(
                'exts' => array('xlsx', 'xls'),
                'maxSize' => 3145728000,
                'rootPath' => "./Public/",
                'savePath' => 'Uploads/',
                'subName' => array('date', 'Ymd'),
            );
            $upload = new \Think\Upload($config);

            $info = $upload->upload();
            if (!$info) {
                $this->error($upload->getError());
            } else {//上传成功拼接获得上传文件的地址
                // $filename=ROOT.'/Public'.$info['excel']['savepath'].$info['excel']['savename'];
                $filename = $upload->rootPath . $info['files']['savepath'] . $info['files']['savename'];
                require_once THINK_PATH.'Library/Org/Util/PHPExcel/IOFactory.php';
                $reader =\PHPExcel_IOFactory::createReader('Excel5');
                $PHPExcel = $reader->load($filename);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumm = $sheet->getHighestColumn(); // 取得总列数
                $data = array();
                $stu_model = M('stu');
             //   var_dump($stu_model);
             //   die();
                for ($row = 2; $row <= $highestRow; $row++){//行数是以第1行开始
                    $dataset = array();
                    for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
                        $dataset[] = (string)$sheet->getCell($column.$row)->getValue();
                    }

                    $exe_id_number = trim($dataset[2]);
                    //查询是否存在
                    $stus = $stu_model->where(array('ID_number'=>$exe_id_number))->find();

                    var_dump($dataset);
                    var_dump($stus);

                  //  die();
                    if($stus){

                        $insert_data=array();
                        if($stus['town']=='杨峪河'){
                            $insert_data['town'] = '杨峪河镇';
                        }
                        $fenge = '镇';
                        $address_array = explode($fenge, $dataset[7]);
                        if(!is_array($address_array)){
                            $fenge = '处';
                            $address_array = explode('处', $dataset[7]);
                        }
                        if(!is_array($address_array)) {
                            $fenge = '乡';
                            $address_array = explode('乡', $dataset[7]);
                        }

                        if(is_array($address_array)){
                            $insert_data['town'] = $address_array[0].$fenge;     //乡镇
                            $insert_data['address'] = $address_array[1];
                        }

                        if(strpos($dataset[7],'刘湾')){
                            $insert_data['town'] = '刘湾街道办事处';
                        }




                        var_dump($insert_data);
                    //    var_dump($stus);
                       die();
                        $stu_list = $stu_model->where("id=".$stus['id'])->save($insert_data);
                      //  var_dump($insert_data);

                    }


                }
            echo "OVER";
                //数据导入成功之后的跳转操作

            }
        }

    }


    /**
     * 学籍号导入
     */

    public function xuejihao()
    {
        ini_set('memory_limit', '1024M');
        if (!empty($_FILES)) {
            $config = array(
                'exts' => array('xlsx', 'xls'),
                'maxSize' => 3145728000,
                'rootPath' => "./Public/",
                'savePath' => 'Uploads/',
                'subName' => array('date', 'Ymd'),
            );
            $upload = new \Think\Upload($config);
            $grade_model = M("grade");
            $class_model = M("shclass");
            $info = $upload->upload();
            if (!$info) {
                $this->error($upload->getError());
            } else {//上传成功拼接获得上传文件的地址
                // $filename=ROOT.'/Public'.$info['excel']['savepath'].$info['excel']['savename'];
                $filename = $upload->rootPath . $info['files']['savepath'] . $info['files']['savename'];
                require_once THINK_PATH.'Library/Org/Util/PHPExcel/IOFactory.php';
                $reader =\PHPExcel_IOFactory::createReader('Excel5');
                $PHPExcel = $reader->load($filename);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumm = $sheet->getHighestColumn(); // 取得总列数
                $data = array();
                $stu_model = M('stu');
                for ($row = 2; $row <= $highestRow; $row++){//行数是以第1行开始
                    $dataset = array();
                    for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
                        $dataset[] = $sheet->getCell($column.$row)->getValue();
                    }
                    //查询是否存在
                    $id_number = $dataset[2];
                    $id_name = $dataset[1];
                    $xj_number = $dataset[0];

                    $stus = $stu_model->where(array('ID_number'=>$id_number,'name'=>$id_name))->find();

                    //如果姓名为空，全部跳出
                    if(!$id_name){
                        break;
                    }

                    //变量准备开始  年级  这块省略

                    $tyear = intval(substr($id_number, 6, 4));
                    $tmonth = intval(substr($id_number, 10, 2));
                    $tday = intval(substr($id_number, 12, 2));
                    $birthday = $tyear . '-' . $tmonth . '-' . $tday;

                    $sexint = (int) substr($id_number, 16, 1);
                    $sex=$sexint % 2 === 0 ? '女' : '男';


                    $insert_data=array(
                        'name' => $id_name,
                        'sex' => $sex,
                        'ID_number' => $id_number,
                        'XJ_number' => $xj_number,
                        'birthday' => $birthday
                    );


                    if($stus){
                        //存在，更新学籍号
                        $stu_list = $stu_model->where("id=".$stus['id'])->save($insert_data);
                    }else{
                        $result = $stu_model->add($insert_data);
                    }

                }

                //数据导入成功之后的跳转操作
                $this->success('导入成功', U('Admin/Stu/showAll'), 3);
            }
        }

    }

    /**
     * 学籍号导入
     */

    public function xueji_system()
    {
        ini_set('memory_limit', '1024M');
        if (!empty($_FILES)) {
            $config = array(
                'exts' => array('xlsx', 'xls'),
                'maxSize' => 3145728000,
                'rootPath' => "./Public/",
                'savePath' => 'Uploads/',
                'subName' => array('date', 'Ymd'),
            );
            $upload = new \Think\Upload($config);
            $grade_model = M("grade");
            $class_model = M("shclass");
            $info = $upload->upload();
            if (!$info) {
                $this->error($upload->getError());
            } else {//上传成功拼接获得上传文件的地址
                // $filename=ROOT.'/Public'.$info['excel']['savepath'].$info['excel']['savename'];
                $filename = $upload->rootPath . $info['files']['savepath'] . $info['files']['savename'];
                require_once THINK_PATH.'Library/Org/Util/PHPExcel/IOFactory.php';
                $reader =\PHPExcel_IOFactory::createReader('Excel5');
                $PHPExcel = $reader->load($filename);
                $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $highestColumm = $sheet->getHighestColumn(); // 取得总列数



                $data = array();
                $stu_model = M('stu');
                $cg_number = 0;
                $sb_number = 0;

                for ($row = 2; $row <= $highestRow; $row++){//行数是以第1行开始
                    $dataset = array();
                    for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
                        $dataset[] = $sheet->getCell($column.$row)->getValue();
                    }

                    //查询是否存在
                    $id_number = $dataset[2];  //身份证号
                    $id_name = $dataset[0];  //姓名
                    $xj_number = $dataset[1];  //学籍号
                    $father_name=$dataset[3];  //父名
                    $father_ID_number=$dataset[4];  //父身份证号
                    $mother_name=$dataset[5];  //母名
                    $mother_ID_number=$dataset[6];  //母身份证号


                    $stus = $stu_model->where(array('ID_number'=>$id_number,'name'=>$id_name))->find();
                  //  var_dump($stus);

                    //如果姓名为空，全部跳出
                    if(!$id_name){
                        break;
                    }

                    //变量准备开始  年级  这块省略

                    $tyear = intval(substr($id_number, 6, 4));
                    $tmonth = intval(substr($id_number, 10, 2));
                    $tday = intval(substr($id_number, 12, 2));
                    $birthday = $tyear . '-' . $tmonth . '-' . $tday;

                    $sexint = (int) substr($id_number, 16, 1);
                    $sex=$sexint % 2 === 0 ? '女' : '男';


                    $insert_data=array(
                        'name' => $id_name,
                        'sex' => $sex,
                        'ID_number' => $id_number,
                        'XJ_number' => $xj_number,
                        'birthday' => $birthday
                    );


                    if($father_name){
                        $insert_data['father_name'] = $father_name;
                    }
                    if($father_ID_number){
                        $insert_data['father_ID_number'] = $father_ID_number;
                    }
                    if($mother_name){
                        $insert_data['mother_name'] = $mother_name;
                    }
                    if($mother_ID_number){
                        $insert_data['mother_ID_number'] = $mother_ID_number;
                    }



                    if($stus){
                        $stu_list = $stu_model->where("id=".$stus['id'])->save($insert_data);
                    }
                    if($stu_list){
                        $cg_number += 1;
                        echo json_encode($insert_data);
                        echo "<br>";
                    }else{
                        $sb_number += 1;
                        echo "<font color='red'>".json_encode($insert_data)."</font>";
                        echo "<br>";
                    }

                }
                echo "成功导入数量：{$cg_number},失败数量：{$sb_number}";
                //数据导入成功之后的跳转操作
                //$this->success('导入成功', U('Admin/Stu/showAll'), 3);
            }
        }

    }

    /**
     * 缓存清理
     */
    public function cache_del() {

        function delFileByDir($dir) {
            $dh = opendir($dir);
            while ($file = readdir($dh)) {
                if ($file != "." && $file != "..") {

                    $fullpath = $dir . "/" . $file;
                    if (is_dir($fullpath)) {
                        delFileByDir($fullpath);
                    } else {
                        unlink($fullpath);
                    }
                }
            }
            closedir($dh);
        }

        delFileByDir(APP_PATH.'Runtime/');
        $this->success('删除缓存成功！',U('Admin/Index'));
    }

}